<template>
  <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
    <el-tab-pane label="销售出库" name="first">
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="销售订单编号" prop="bpsSn" label-width="55">
            <el-input
              v-model="queryParams.orderSn"
              placeholder="请输入销售订单编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['mes:retrieval:add']"
            >新增出库单</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="success"-->
<!--              plain-->
<!--              icon="el-icon-edit"-->
<!--              size="mini"-->
<!--              :disabled="single"-->
<!--              @click="handleUpdate"-->
<!--              v-hasPermi="['mes:retrieval:edit']"-->
<!--            >修改</el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['mes:retrieval:export']"
            >导出</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="retrievalList"border style="width: 100%" @selection-change="handleSelectionChange">
<!--          <el-table-column type="selection" width="55" align="center" />-->
<!--          <el-table-column label="id" align="center" prop="id" />-->
          <el-table-column label="状态" align="center" prop="dfsState" >
            <template v-slot = "scope">
              <dict-tag :options="dict.type.storage_out_state" :value="scope.row.dfsState"/>
            </template>
          </el-table-column>
          <el-table-column label="出库编号" align="center" prop="dfsSn" />
          <el-table-column label="销售订单编号" align="center" prop="orderSn" />
<!--          <el-table-column label="产品库存id" align="center" prop="proStrmId" />-->
<!--          <el-table-column label="出库数量" align="center" prop="dfsNum" />-->
<!--          <el-table-column label="出库数量" align="center" prop="dfsRenum" />-->
          <el-table-column label="出库人" align="center" prop="userId" />
<!--          <el-table-column label="出库类型" align="center" prop="dfsType" />-->
          <el-table-column label="出库日期" align="center" prop="dfsDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.dfsDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建者" align="center" prop="createdBy" />
          <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-check"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['mes:retrieval:edit']"
              >出库</el-button>
<!--              <el-button-->
<!--                size="mini"-->
<!--                type="text"-->
<!--                icon="el-icon-delete"-->
<!--                @click="handleDelete(scope.row)"-->
<!--                v-hasPermi="['mes:retrieval:remove']"-->
<!--              >删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改出库管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-divider>产品列表</el-divider><!--分割线-->
            <el-row type="flex" align="middle" v-if="title=='添加出库单'">
              <el-col :span="12">
                <el-form-item label="销售订单" prop="userId">
                  <el-select v-model="form.orderSn" placeholder="请选择销售订单" @change="handleSellOrderChange">
                    <el-option
                      v-for="item in sellOrderList"
                      :key="item.id"
                      :label="`${item.orderName}/${item.orderSn}`"
                      :value="item.orderSn"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出库人" prop="userId">
                  <el-select v-model="form.userId" placeholder="请选择出库人">
                    <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="`${item.userName}/${item.nickName}`"
                      :value="item.userName"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row type="flex" align="middle" v-else>
              <el-col :span="12">
                <el-form-item label="销售订单" prop="orderSn">
                  <el-select v-model="form.orderSn" placeholder="请选择销售订单" @change="handleSellOrderChange" :disabled="true">
                    <el-option
                      v-for="item in sellOrderList"
                      :key="item.id"
                      :label="`${item.orderName}/${item.orderSn}`"
                      :value="item.orderSn"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出库人" prop="userId">
                  <el-select v-model="form.userId" placeholder="请选择出库人" :disabled="true">
                    <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="`${item.userName}/${item.nickName}`"
                      :value="item.userName"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-card shadow="always" style="border-radius: 15px;">
              <el-table border style="width: 100%" v-loading="loading" :data="sellOrderProList">
                <el-table-column label="产品名称" prop="proName" :width="150">
                </el-table-column>
                <el-table-column label="产品编码" prop="proSn">
                </el-table-column>
                <el-table-column v-if="title=='销售出库确认'" label="成品库" >
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.strmId" placeholder="请选择仓库" @change="leftNumChange(scope.row)">
                      <el-option
                        v-for="item in scope.row.strmList"
                        :key="item.id"
                        :label="`${item.strmName}/${item.strmSn}`"
                        :value="item.strmId"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column v-if="title=='销售出库确认'" label="仓库产品剩余容量" :width="150">
                  <template slot-scope="scope">
                        <span>{{ scope.row.leftNum }}</span>
                  </template>
                </el-table-column>
                <el-table-column v-if="title=='销售出库确认'" label="需出库数量" :width="90">
                  <template slot-scope="scope">
                    <span>{{ scope.row.proNum }}</span>
                  </template>
                </el-table-column>
                <el-table-column v-if="title=='销售出库确认'" label="以出库数量" :width="90">
                  <template slot-scope="scope">
                    <span>{{ scope.row.proRenum }}</span>
                  </template>
                </el-table-column>
                <el-table-column v-if="title=='添加出库单'" label="产品需出库数量" prop="num">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.proNum" controls-position="right"  :min="1" :max="scope.row.deviNum "></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column v-else label="产品出库数量" prop="num">
                  <template slot-scope="scope">
                    <el-input-number v-if="scope.row.leftNum>(scope.row.proNum-scope.row.proRenum)" v-model="scope.row.tempNum" controls-position="right"  :min="0" :max="scope.row.proNum-scope.row.proRenum"></el-input-number>
                    <el-input-number v-else v-model="scope.row.tempNum" controls-position="right"  :min="0" :max="scope.row.leftNum"></el-input-number>
                  </template>
                </el-table-column>
<!--                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-button  size="mini" type="text" icon="el-icon-check" @click="mtroutadd(scope.$index)">增加</el-button>-->
<!--                    <el-button  size="mini" type="text" icon="el-icon-check" @click="mtroutdel(scope.$index)">删除</el-button>-->
<!--                  </template>-->
<!--                </el-table-column>-->
              </el-table>
            </el-card>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-tab-pane>
    <el-tab-pane label="物料出库" name="second">
      <child1 v-if="isChildUpdate2"></child1>
    </el-tab-pane>
  </el-tabs>

</template>

<script>
import { listRetrieval, getRetrieval, delRetrieval, addRetrieval, updateRetrieval, addNewRetrieval, getNewRetrieval,updateNewRetrieval} from "@/api/mes/retrieval";
import {listSell_order, getSell_orderPro} from "@/api/mes/sell_order";
import {listUser} from "@/api/system/user";
import {listInventory} from "@/api/mes/inventory";
import firstComponent from "@/views/mes/retrieval/materialOutbound";
import item from "@/layout/components/Sidebar/Item";

export default {
  name: "Retrieval",
  dicts:["storage_out_state"],
  components: {
    child1: firstComponent,
  },
  data() {
    return {
      // 默认第一个选项卡
      activeName: 'first',
      // 初始化两个变量 isChildUpdate1:true，isChildUpdate2:false；
      // 使用v-if控制child1和child2是否渲染。
      // 每次切换tab选项的时候，触发事件。让当前点击的tab变量设置位true，让当前组件重新渲染。
      // 这时候当你来回切换的时候，通过v-if判断是否重新渲染当前组件
      isChildUpdate2: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库管理表格数据
      retrievalList: [],
      //销售订单列表
      sellOrderList:[],
      //销售订单绑定的产品列表
      sellOrderProList:[],
      //出库人列表
      userList:[],
      //临时表
      tempStrmList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParamsSellOrder: {
      },
      queryParamsUser: {
      },
      queryParamsStrm: {
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getOrderList();
    this.getUserList();
    this.getstrmList();
  },
  methods: {
    leftNumChange(row){
      row.strmId=parseInt(row.strmId)
      const ss = row.strmList.find(item =>item.strmId==row.strmId)
      if(ss){

        row.leftNum=ss.proNum;
      }
    },
    getstrmList(){
      listInventory(this.queryParamsStrm).then(response =>{
        this.tempStrmList=response.rows;
        console.log("adwdawwdaerwe",this.tempStrmList)
      });
    },

    handleClick (tab) {
      if (tab.name === 'second') {
        this.isChildUpdate2 = true
      } else if (tab.name === 'first') {
        this.isChildUpdate2 = false
      }
    },

    handleSellOrderChange(){
      const ss = this.sellOrderList.find(item => item.orderSn == this.form.orderSn)
      console.log(ss)
      if(ss){
          this.form.orderId=ss.id;
      }
      getSell_orderPro(this.form.orderId).then(response => {
        this.sellOrderProList = response.rows;
        console.log("5415849",this.form)
      });
    },

    /** 查询出库人 */
    getUserList() {
      this.loading = true;
      // const dfsType = 0;
      listUser(this.queryParamsUser).then(response => {
        this.userList = response.rows;
        this.loading = false;
      });
    },

    /** 查询销售订单 */
    getOrderList() {
      this.loading = true;
      // const dfsType = 0;
      listSell_order(this.queryParamsSellOrder).then(response => {
        this.sellOrderList = response.rows;
        this.loading = false;
      });
    },

    /** 查询出库管理列表 */
    getList() {
      this.loading = true;
      const dfsType = 0;
      var tempList =[];
      listRetrieval(this.queryParams).then(response => {
        this.retrievalList = response.rows;
        this.retrievalList = this.retrievalList.filter(item => item.dfsType == dfsType)
        this.retrievalList.forEach((item) => {
          getNewRetrieval(item.id).then(response =>{
            tempList=response.rows;
            if(tempList.length>0)
            {
              item.userId= tempList[0].outerName;
            }
          });
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dfsSn: null,
        proStrmId: null,
        dfsNum: null,
        userId: null,
        orderId: null,
        dfsType: null,
        dfsDate: null,
        dfsState: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加出库单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRetrieval(id).then(response => {
        this.form = response.data;
        getNewRetrieval(id).then(response =>{
          this.sellOrderProList=response.rows;
          this.form.userId=this.sellOrderProList[0].outerName;
          this.form.orderId=parseInt(this.sellOrderProList[0].orderId);
          this.sellOrderProList.forEach((item)=>{
             item.strmList=this.tempStrmList.filter(ss => ss.proId == item.proId)
            console.log("item.strmList",item.strmList)
          })
        });
        this.open = true;
        this.title = "销售出库确认";
      });
    },
    /** 提交按钮 */
    submitForm() {
      var Num=0;
      var Renum=0;
      var AllNum=0;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            console.log("update",this.sellOrderProList)
            this.sellOrderProList.forEach((item)=>{
              Num=Num+item.tempNum;
              Renum=Renum+item.proRenum;
              AllNum=AllNum+item.proNum;
            })
            if((Num+Renum)<AllNum){
              this.form.dfsState=1;
            }
            else {
              this.form.dfsState=2;
            }
            updateRetrieval(this.form).then(response => {
              updateNewRetrieval(this.sellOrderProList).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.getstrmList();
              });
            });
          } else {
            this.sellOrderProList.forEach((item)=>{
              item.id=null;
              item.orderId=this.form.orderId;
              item.orderSn=this.form.orderSn;
              item.outerName=this.form.userId;
            });
            console.log("dadwaw",this.form)
            addNewRetrieval(this.sellOrderProList).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除出库管理编号为"' + ids + '"的数据项？').then(function() {
        return delRetrieval(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/retrieval/export', {
        ...this.queryParams
      }, `retrieval_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
